const serve = require('serve');
const chokidar = require('chokidar');
const nodepath = require('path');
const babel = require('babel-core');
const fs = require('fs-extra');

//该脚本用户监听src文件夹中js文件的变化，开发中随时更新js文件夹中的文件
chokidar.watch('src', {ignored: /(^|[\/\\])\.js+/}).on('all', (event, path) => {
  const ext = nodepath.extname(path);
  if(ext==='.js'){
      console.log(event, path);
      // console.log(babel.transformFileSync(path).code);
      // 文件转码（异步）
      babel.transformFile(path, {
          presets: [
              "env",
              "react",
              "stage-2"
          ]
      }, function(err, result) {
          if(err){
              console.log(err);
              return;
          }
          // console.log(result.code);
        const pathobj = nodepath.parse(path);
        const dir = nodepath.dirname(path);
        const subdir = dir.slice(dir.indexOf("\\")+1);
        if(subdir==='src'){
            const output = 'js\\'+pathobj.base;
            fs.ensureDirSync(nodepath.dirname(output));
            fs.writeFileSync(output,result.code);
            console.log('output to '+output);
        }
        else{
            const output = 'js\\'+subdir+'\\'+pathobj.base;
            fs.ensureDirSync(nodepath.dirname(output));
            fs.writeFileSync(output,result.code);
            console.log('output to '+output);
        }
        // fs.writeFileSync('js\\'+subdir+'\\'+pathobj.base,result);
          // result; // => { code, map, ast }
      });
  }
});
const server = serve('.', {
  port: 3000
});